package com.gmrz.uap.policy;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.gmrz.uap.cfg.SystemConst;
import com.gmrz.uap.common.ServiceSupport;
import com.gmrz.uap.model.AuthMetadata;
import com.gmrz.uap.model.Policy;
import com.gmrz.uap.model.PolicyAuth;
import com.gmrz.uap.util.Identities;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import org.apache.commons.lang3.StringUtils;

import java.util.List;

public class PolicyService extends ServiceSupport {

    public static final PolicyService me = new PolicyService();

    /**
     * 保存策略
     *
     * @param plId    策略id
     * @param authIds 元数据id数组
     */
    public boolean savepolicyAuth(String plId, String[] authIds, String tenantId) {
        PolicyAuth policyAuth = new PolicyAuth();
        policyAuth.setPlId(plId);

        for (String metadataId : authIds) {
            policyAuth.setMetadataId(metadataId);
            flag = policyAuth.save();
        }

        return flag;
    }

    /**
     * 保存策略名
     *
     * @param policy
     */
    public boolean savePolicy(Policy policy, String tenantId) {

        StringBuilder sb = new StringBuilder();
        sb.append(SystemConst.POLICY_NAME).append("_").append(tenantId);

        if (StringUtils.isNotBlank(policy.getAuthType())) {
            sb.append("_").append(policy.getAuthType());
        }

        if (StringUtils.isNotBlank(policy.getTransType())) {
            sb.append("_").append(policy.getTransType());
        }

        policy.setPolicyName(sb.toString());

        List<Policy> allPolicys = Policy.dao.getPolicy(null, tenantId);
        for (Policy p : allPolicys) {
            if (p.getPolicyName().equals(policy.getPolicyName())) {
                return false;
            }
        }
        policy.setPlId(policy.getPlId());
        policy.setTenantId(tenantId);

        flag = policy.save();

        return flag;
    }

    /**
     * 删除policy
     *
     * @param policy 策略信息
     */
    public boolean removePolicy(Policy policy, String tanentid) {

        String plId = policy.getPlId();

        PolicyAuth.dao.deleteByPlId(plId);

        flag = Policy.dao.deleteById(plId);

        return flag;
    }

    /**
     * @return 返回policy.json文件字符串
     */
    private String getJsonString2(String tenantid) {
        List<Policy> policys = Policy.dao.getPolicy(null, null);
        JSONObject jsonObject = new JSONObject();//根结点
        if (policys != null && policys.size() > 0) {
            for (Policy p : policys) {
                JSONObject policyName = new JSONObject();//策略名
                JSONArray policyArray = new JSONArray();//策略数组
                List<AuthMetadata> authMetadata = p.getAuthMetadata(tenantid);
                if (authMetadata != null && authMetadata.size() > 0) {
                    for (int x = 0; x < authMetadata.size(); x++) {
                        JSONArray policy = new JSONArray();//策略数组内层数组
                        JSONObject policyData = new JSONObject();//aaid数据对象
                        JSONArray aaid = new JSONArray();//aaid数组
                        aaid.add(0, authMetadata.get(x).getAaid());
                        policyData.put("aaid", aaid);
                        policy.add(0, policyData);
                        policyArray.add(x, policy);
                    }
                }
                policyName.put("accepted", policyArray);
                jsonObject.put(p.getPolicyName(), policyName);
            }
        }
        return jsonObject.toJSONString();
    }

    /**
     * @return 返回policy.json文件字符串
     */
    private String getJsonString(String tenantid) {
        List<Policy> policys = Policy.dao.getPolicy(null, tenantid);
        JSONObject jsonObject = new JSONObject();//根结点
        if (policys != null && policys.size() > 0) {
            for (Policy p : policys) {
                JSONObject policyName = new JSONObject();//策略名
                JSONArray policyArray = new JSONArray();//策略数组
                List<AuthMetadata> authMetadata = p.getAuthMetadata(tenantid);
                if (authMetadata != null && authMetadata.size() > 0) {
                    for (int x = 0; x < authMetadata.size(); x++) {
                        JSONArray policy = new JSONArray();//策略数组内层数组
                        JSONObject policyData = new JSONObject();//aaid数据对象
                        JSONArray aaid = new JSONArray();//aaid数组
                        aaid.add(0, authMetadata.get(x).getAaid());
                        policyData.put("aaid", aaid);
                        policy.add(0, policyData);
                        policyArray.add(x, policy);
                    }
                }
                policyName.put("accepted", policyArray);
                jsonObject.put(p.getPolicyName() + ":" + tenantid, policyName);
            }
        }

        return jsonObject.toJSONString();
    }

    /**
     * 当策略信息发生变更的时候，同时更新文件和缓存中的信息
     *
     * @param tenantId
     */
   /* public boolean updatePolicyJson(String tenantId) throws JedisConnectionException {
        boolean flag = true;
        String policyJsonInfo = getJsonString(tenantId);//根据租户ID获取策略信息
        String policyJsonInfo2 = getJsonString2(tenantId);//根据租户ID获取策略信息
        boolean devMode = PropKit.use("application.properties").getBoolean("devMode");
        String policyPath;

        //如果是开发模式获取配置文件中的路径，如果是生产环境则获取数据库中的路径
        if (devMode) {
            policyPath = PropKit.use("application.properties").get("policyPath");
        } else {
            policyPath = UasConfigContentService.me.getUafPolicyJsonFile();
        }

        if (StrKit.notBlank(policyPath)) {//路径是否为空
            File policyFile = new File(policyPath);
            if (policyFile.exists()) {//文件是否存在
                IOUtils.String2File(policyJsonInfo2, policyFile);
            }
        }

        //获取缓存实例
        loger.info("缓存中存储policy===============================" + policyJsonInfo2);
        try {
            CacheStoreService cacheStoreService = AmmsCacheUtil.getCacheStoreService();
            cacheStoreService.set(AmmsCacheUtil.POLICYJSON, policyJsonInfo2);
        } catch (JedisConnectionException e) {
            flag = false;
            throw new JedisConnectionException(e);
        }

        return flag;
    }*/

    /**
     * @return 返回所有策略 List<Policy>
     */
    public List<Policy> findAll(String tanentid) {
        return Policy.dao.getPolicy(null, tanentid);
    }


    public Policy findLastInsert(String tenantId) {
        return Policy.dao.findLastInsert(tenantId);
    }

    public List<AuthMetadata> getDefaultPolicy(Policy policy, String tenantid) {
        return Policy.dao.getDefaultPolicy(policy, tenantid);
    }

    public List<AuthMetadata> getPolicyAaid(String plid, String tenantid) {
        return Policy.dao.getAuthMetadataByPlid(plid);
    }

    public List<PolicyAuth> findAllPolicyAuth(String pl_id) {
        List<PolicyAuth> byPlID = PolicyAuth.dao.findByPlID(pl_id);
        return byPlID;
    }

    public boolean removeByPolicyIdAndMetadataId(String policyId, String[] ids, String tenantId) {
        boolean flag = PolicyAuth.dao.removeByPolicyIdAndMetadataId(policyId, ids);

        return flag;
    }


    public boolean exist(String policyName) {
        return null != Policy.dao.getByPolicyName(policyName);
    }


    public Page<Record> policyConfigListByPolicyId(int page, int rows, String sort, String order, String policyId) {
        String selectsql = "select policy_config_id, config_name, config_value, des, createts  ";
        String sql = "from t_policy_config where policy_id ='"+policyId+"'";
        return Db.paginate(page,rows,selectsql,sql);
    }

}
